from django_redis import get_redis_connection
from rest_framework import serializers
from django.core.mail import send_mail
from .models import User
from django.conf import settings
from celery_tasks.email.tasks import send_verify_url


class RegiserUserSerializer(serializers.ModelSerializer):
    # write_only 只写,只校验,不入库.也不需要返回前段浏览
    password2 = serializers.CharField(min_length=8,max_length=20,label="确认密码",write_only=True)
    sms_code = serializers.CharField(min_length=6,max_length=6,label="短信验证码",write_only=True)
    allow = serializers.CharField(label="协议",write_only=True)
    token = serializers.CharField(label="jwt口令",read_only=True)
    class Meta:
        model = User
        fields = ("id","username","password","password2","mobile","sms_code","allow","token")

        read_only_fields = ["id"]

        extra_kwargs  ={
            "password":{
                "min_length":8,
                "max_length":20
            }
        }


    #1单字段校验allow协议
    def validate_allow(self,value):

        if value != "True":
            raise  serializers.ValidationError("必须同意协议")

        return value


    #2.校验多字段,密码,短信
    def validate(self,attrs):

        #0.取出手机号和短信验证码
        sms_code  = attrs["sms_code"]
        moblie  =  attrs["moblie"]

        #1.校验密码
        if attrs["password"] !=attrs["password2"]:
            raise serializers.ValidationError("两次密码不相等")

        #2.校验短信
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%moblie)

        #3.判断是否过期
        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码已经过期")

        #4.校验
        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("短信验证码填写错误")

        #返回
        return  attrs

    #3 由于User表中没有password2,sms_code,allow.所以需要去除
    def create(self,validate_data):
        #1.去除不需要的数据/
        del validate_data["password2"]
        del validate_data["sms_code"]
        del validate_data["allow"]

        #2.创建对象
        user = super(RegiserUserSerializer,self).create(validate_data)

        #2.2密码加密
        user.set_password(validate_data["password"])
        user.save()

        from rest_framework_jwt.settings import api_settings
        #设置JWT
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        #3.返回
        return user


class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("id", "username", "email", "email_active")


class EmailSendserializer(serializers.Serializer):
    email = serializers.EmailField(label="邮箱")

    def update(self, instance, validate_data):
        # 1.将邮箱设置成用户对象
        email = validate_data["email"]
        instance.email = email
        instance.save()

        # 2.发送邮件
        verify_url = instance.generate_verify_url()
        # send_mail(subject="请你点击验证,来自美多国际商城", message="verify_url", from_email=settings.EMAIL_FROM, recipient_list=[email])
        send_verify_url.delay(verify_url,email)
        # 3.返回
        return validate_data
